﻿using System;
using System.Windows;
using DataBaseLibrary.DBInterfaces;
using DataBaseLibrary.DBObjectsFB;
using DocMreoLiteVersion.Reports.SaleContractReport;
using DocMreoLiteVersion.Reports.DeclarationReport;
using System.Linq;
using System.Xml;
using System.IO;

namespace DocMreoLiteVersion
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        private IDBProvider db_provider = null;

        public MainWindow()
        {


            //TODO: Читать настройки потом из конфига к приложению (xml). Если его нет, то создать. В качестве имени мьютекса использовать GUID. генерировать его при создании конфига
            //следующим образом: System.GUID.NewGuid().ToString()
            bool mutex_app;
            using (System.Threading.Mutex m = new System.Threading.Mutex(true, "{1-8996-3665-112-33654}", out mutex_app))
            {

                //MessageBox.Show(mutex_app.ToString());
                if (!mutex_app)
                    System.Windows.Application.Current.Shutdown();
            }

            InitializeComponent();
        }

        private bool ConnectDB(String PathDB)
        {
            db_provider = new FDBProvider(PathDB, "SYSDBA", "masterkey");
            return db_provider.Connect();
        }

        

        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            CSettings.LoadSettings();            
            if (!ConnectDB(CSettings.PathDB + "DOCMREODB.FDB"))
            {
                MessageBox.Show("Ошибка при подключении к базе данных. \nОбращайтесь к разработчикам", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            //Настройки и соединение с базой данных
            m_DetailGrid.Children.Clear();
            FormChoiseDocument choise_document = new FormChoiseDocument();
            choise_document.ShowFormSalesContract += choise_document_ShowFormSalesContract;
            choise_document.ShowFormDeclarationContract += choise_document_ShowFormDeclarationContract;
            m_DetailGrid.Children.Add(choise_document);
        }

        void f_contract_CloseFormContracts(object sender, RoutedEventArgs e)
        {
            m_DetailGrid.Children.Clear();
            FormChoiseDocument choise_document = new FormChoiseDocument();
            choise_document.ShowFormSalesContract += choise_document_ShowFormSalesContract;
            choise_document.ShowFormDeclarationContract += choise_document_ShowFormDeclarationContract;
            m_DetailGrid.Children.Add(choise_document);
        }


        /********    События от документов ******************************/

        void choise_document_ShowFormDeclarationContract(object sender, RoutedEventhoiseDocumentArgs e)
        {
            m_DetailGrid.Children.Clear();
            FormDeclarationReport f_contract = new FormDeclarationReport(db_provider, e.DocumentNumber);
            f_contract.CloseFormDeclarationReportContract += f_contract_CloseFormContracts;
            m_DetailGrid.Children.Add(f_contract);
        }

        void choise_document_ShowFormSalesContract(object sender, RoutedEventhoiseDocumentArgs e)
        {
            m_DetailGrid.Children.Clear();
            FormSalesContract f_contract = new FormSalesContract(db_provider, e.DocumentNumber);
            f_contract.CloseFormSalesContract += f_contract_CloseFormContracts;
            f_contract.CreateDeclaration += f_contract_CreateDeclaration;
            m_DetailGrid.Children.Add(f_contract);
        }

        void f_contract_CreateDeclaration(object sender, FormSalesContract.RoutedEventCreateDeclarationArgs e)
        {
            //m_DetailGrid.Children.Clear();
            (sender as FormSalesContract).Visibility = Visibility.Hidden;
            FormDeclarationReport f_contract = new FormDeclarationReport(db_provider, e.Owner, e.Representative, e.MVechicle);
            f_contract.CloseFormDeclarationReportContract += f_contract_ReturnSalesContractFromDeclaration;
            m_DetailGrid.Children.Insert(0, f_contract);
        }



        void f_contract_ReturnSalesContractFromDeclaration(object sender, RoutedEventArgs e)
        {
            m_DetailGrid.Children.RemoveAt(0);
            m_DetailGrid.Children[0].Visibility = Visibility.Visible;            
        }

        private void Window_Closed_1(object sender, EventArgs e)
        {
            if (db_provider != null)
                db_provider.CloseConnect();
        }


        private void SettingApplicationItem(object sender, RoutedEventArgs e)
        {
            SettingWindow setting = new SettingWindow(db_provider);
            setting.Owner = this;
            setting.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            setting.ShowDialog();
        }

        private void About_Click(object sender, RoutedEventArgs e)
        {
            AboutWindow about_window = new AboutWindow();
            about_window.Owner = this;
            //about_window. Переместить в центр
            about_window.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            about_window.ShowDialog();
        }
    }
}
